package com.whately.core.base.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA256 摘要算法工具类
 *
 */
@Slf4j
public class SHA256Util {

    public static String sha256(String message){
        return new String(Hex.encodeHex(sha256Digest(message)));
    }

    /**
     * 利用java原生的摘要实现SHA256加密
     */
    private static byte[] sha256Digest(String str) {
        MessageDigest messageDigest;
        byte[] bytes = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            bytes = messageDigest.digest();
        } catch (NoSuchAlgorithmException e) {
            log.error("sha256 NoSuchAlgorithmException error ",e);
        }
        return bytes;
    }


}
